package com.shujia.scala

import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}
import org.junit.Test

class Demo13Json {

  @Test
  def parseObject(): Unit = {
    //""" 可以用于换行字符串，|会被自动去掉
    val jsonStr: String =
      """
        |{
        |    "id":"001",
        |    "name":"张三",
        |    "age":23,
        |    "gender":"爸爸",
        |    "爱好":["打游戏","打球"]
        |}
        |""".stripMargin

    /**
     * 使用fastjson解析json字符串
     *
     */

    //将json字符串转换成json对象,使用json对象可以通过key获取value
    val jsonObj: JSONObject = JSON.parseObject(jsonStr)
    //通过key获取value
    val id: String = jsonObj.getString("id")
    val name: String = jsonObj.getString("name")
    val age: Int = jsonObj.getInteger("age")
    val gender: String = jsonObj.getString("gender")

    val array: JSONArray = jsonObj.getJSONArray("爱好")

    println(s"$id\t$name\t$age\t$gender\t$array")
  }

  @Test
  def parseCLass(): Unit = {
    val jsonStr: String =
      """
        |{
        |    "id":"001",
        |    "name":"张三",
        |    "age":23,
        |    "gender":"爸爸",
        |    "live":["打游戏","打球"]
        |}
        |""".stripMargin

    //将一个json字符串转换成对象
    //这里写scala代码不能使用内部类
    val student: Student2 = JSON.parseObject(jsonStr, classOf[Student2])
    println(student)
    println(student.name)
  }

}

//样例类
case class Student2(id: String, name: String, age: Int, gender: String, live: Array[String])
